﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading;
using System.Text;
using System.IO;

/// <summary>
///LogWriter 的摘要说明
/// </summary>
public class LogWriter
{
    public static Thread LogWriterThread = new Thread(new ParameterizedThreadStart(WriteThreadStart));
    public static StringBuilder loginfo = new StringBuilder();
    //public static StreamWriter writer = new StreamWriter("D:\\qqlog\\logfile.txt", true, Encoding.Default);

	public LogWriter()
	{
		//
		//TODO: 在此处添加构造函数逻辑
		//
	}

    public static void write(string content)
    {
        if (!LogWriterThread.IsAlive)
        {
            LogWriterThread.Start(null);
        }
        lock (loginfo)
        {
            loginfo.AppendLine(content);
        }       

        //writer.AutoFlush = true;
        //writer.WriteLine(content);
    }

    public static void WriteThreadStart(Object obj) 
    {
        while (true) 
        {
            try
            {
                lock (loginfo)
                {
                    using (StreamWriter sw = new StreamWriter("D:\\qqlog\\logfile.txt", true, Encoding.Default))
                    {
                        if (!string.IsNullOrEmpty(loginfo.ToString()))
                        {
                            sw.Write(loginfo.ToString());
                        }
                        sw.Close();
                    }
                    loginfo.Clear();
                }
            }
            catch 
            {

            }
            Thread.Sleep(1000);
        }
    }

    public static void write(string content, string type) 
    {
        try
        {
            string path = "D:\\qqlog\\logfile_" + type + "_" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
            using (StreamWriter sw = new StreamWriter(path, true, Encoding.Default))
            {
                if (!string.IsNullOrEmpty(content))
                {
                    sw.WriteLine(content);
                }
                sw.Close();
            }
        }
        catch { }
    }
}